package com.talent.service.impl;

import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.talent.common.PageResult;
import com.talent.handler.BaseException;
import com.talent.mapper.UserMapper;
import com.talent.pojo.dto.UserDTO;
import com.talent.pojo.entity.User;
import com.talent.service.OperationLogService;
import com.talent.service.UserService;
import com.talent.utils.OperationLogUtils;
import com.talent.utils.PasswordUtil;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

/**
 * 用户服务实现类
 */
@Service
public class UserServiceImpl implements UserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private OperationLogService operationLogService;

    /**
     * 分页查询用户
     */
    @Override
    public PageResult<User> pageQuery(Integer page, Integer pageSize, String search) {
        PageHelper.startPage(page, pageSize);
        Page<User> p = (Page<User>) userMapper.pageQuery(search);
        
        // 清除密码信息
        p.getResult().forEach(user -> {
            user.setPassword(null);
        });

        return new PageResult<>(p.getResult(), p.getTotal(), page, pageSize);
    }

    /**
     * 根据ID查询用户
     */
    @Override
    public User getById(Long id) {
        User user = userMapper.getById(id);
        if (user != null) {
            user.setPassword(null);
        }
        return user;
    }

    /**
     * 新增用户
     */
    @Override
    public void save(UserDTO userDTO) {
        // 检查用户名是否已存在
        User existUser = userMapper.getByUsername(userDTO.getUsername());
        if (existUser != null) {
            throw new BaseException("用户名已存在");
        }

        // 检查手机号是否已存在
        existUser = userMapper.getByPhone(userDTO.getPhone());
        if (existUser != null) {
            throw new BaseException("手机号已存在");
        }

        User user = new User();
        BeanUtils.copyProperties(userDTO, user);
        
        // 设置默认密码和加密
        String defaultPassword = StringUtils.hasText(userDTO.getPassword()) ? 
                userDTO.getPassword() : "123456";
        user.setPassword(PasswordUtil.encode(defaultPassword));

        userMapper.insert(user);

        // 记录详细操作日志（不记录密码信息）
        User logUser = new User();
        BeanUtils.copyProperties(user, logUser);
        logUser.setPassword("******"); // 隐藏密码
        operationLogService.saveDetail(OperationLogUtils.buildCreateLog(
                "user", user.getId(), user.getName(), logUser));
    }

    /**
     * 更新用户
     */
    @Override
    public void update(Long id, UserDTO userDTO) {
        User user = userMapper.getById(id);
        if (user == null) {
            throw new BaseException("用户不存在");
        }

        // 保存更新前的数据（隐藏密码）
        User oldUser = new User();
        BeanUtils.copyProperties(user, oldUser);
        oldUser.setPassword("******");

        // 检查用户名是否已被其他用户使用
        User existUser = userMapper.getByUsername(userDTO.getUsername());
        if (existUser != null && !existUser.getId().equals(id)) {
            throw new BaseException("用户名已存在");
        }

        // 检查手机号是否已被其他用户使用
        existUser = userMapper.getByPhone(userDTO.getPhone());
        if (existUser != null && !existUser.getId().equals(id)) {
            throw new BaseException("手机号已存在");
        }

        BeanUtils.copyProperties(userDTO, user);
        user.setId(id);
        
        // 如果提供了新密码，则更新密码
        if (StringUtils.hasText(userDTO.getPassword())) {
            user.setPassword(PasswordUtil.encode(userDTO.getPassword()));
        }

        userMapper.update(user);

        // 记录详细操作日志（隐藏密码）
        User logUser = new User();
        BeanUtils.copyProperties(user, logUser);
        logUser.setPassword("******");
        operationLogService.saveDetail(OperationLogUtils.buildUpdateLog(
                "user", id, user.getName(), oldUser, logUser));
    }

    /**
     * 删除用户
     */
    @Override
    public void deleteById(Long id) {
        User user = userMapper.getById(id);
        if (user == null) {
            throw new BaseException("用户不存在");
        }

        userMapper.deleteById(id);

        // 记录详细操作日志（隐藏密码）
        User logUser = new User();
        BeanUtils.copyProperties(user, logUser);
        logUser.setPassword("******");
        operationLogService.saveDetail(OperationLogUtils.buildDeleteLog(
                "user", id, user.getName(), logUser));
    }

    /**
     * 重置密码
     */
    @Override
    public void resetPassword(Long id, String newPassword) {
        User user = userMapper.getById(id);
        if (user == null) {
            throw new BaseException("用户不存在");
        }

        // 加密新密码
        user.setPassword(PasswordUtil.encode(newPassword));
        userMapper.update(user);

        // 记录详细操作日志
        operationLogService.saveDetail(OperationLogUtils.buildCustomLog(
                "RESET_PASSWORD", 
                String.format("重置用户密码：%s", user.getName()), 
                "user", 
                id, 
                user.getName()));
    }
}
